<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="18">
        <el-tag>客户资料ID：{{this.business.id}}</el-tag>
        <hr>
        <el-form :disabled="disabled" ref="form" size="mini" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入客户姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职业" prop="occupation">
                <el-select v-model="form.occupation" placeholder="请输入职业">
                  <el-option v-for="dict in dict.type.occupation" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="学历" prop="education">
                <el-select v-model="form.education" placeholder="请输入学历">
                  <el-option v-for="dict in dict.type.education" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所在地区" prop="area">
                <el-cascader
                  v-model="form.area"
                  :options="provinceAndCityDataOptions"
                  @change="handleChangeArea"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微信号" prop="weixin">
                <el-input v-model="form.weixin" placeholder="请输入微信号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="form.age" placeholder="请输入年龄" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="专业" prop="major">
                <el-select v-model="form.major" placeholder="请输入专业">
                  <el-option v-for="dict in dict.type.major" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="在职情况" prop="job">
                <el-select v-model="form.job" placeholder="请输入在职情况">
                  <el-option v-for="dict in dict.type.job" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="当前薪资" prop="salary">
                <el-select v-model="form.salary" placeholder="请输入当前薪资">
                  <el-option v-for="dict in dict.type.salary" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="qq" prop="qq">
                <el-input v-model="form.qq" placeholder="请输入客户qq" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" placeholder="请输入性别">
                  <el-option v-for="dict in dict.type.sys_user_sex" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="目标薪资" prop="expectedSalary">
                <el-select v-model="form.expectedSalary" placeholder="请输入目标薪资">
                  <el-option v-for="dict in dict.type.salary" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" maxlength="120" show-word-limit v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-tag>客户意向</el-tag>
          <hr/>
          <el-row>
            <el-col :span="8">
              <el-form-item label="意向学科" prop="subject">
                <el-select clearable @change="handleChangeSubject" v-model="form.subject" placeholder="请输入意向学科">
                  <el-option v-for="dict in dict.type.course_subject" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="意向课程" prop="courseId">
                <el-select clearable v-model="form.courseId" @change="handleChangeCourse" placeholder="请输入意向课程">
                  <el-option v-for="course in courseOptions" :label="course.name" :value="course.id" :key="course.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="意向金额" prop="price">
                <el-input readonly v-model="form.price" placeholder="请输入客户姓名" />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="学习原因" prop="reasons">
                <el-input v-model="form.reasons" placeholder="请输入学习原因" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职业计划" prop="plan">
                <el-input v-model="form.plan" placeholder="请输入职业计划" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="时间计划" prop="planTime">
                <el-date-picker v-model="form.planTime" placeholder="请输入时间计划"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="其他意向" prop="otherIntention">
                <el-input v-model="form.otherIntention" placeholder="其他意向" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-tag>添加沟通记录</el-tag>
          <hr/>
          <el-row>
            <el-col :span="8">
              <el-form-item label="跟进状态" prop="trackStatus">
                <el-select v-model="form.trackStatus" placeholder="请输入跟进状态">
                  <el-option v-for="dict in dict.type.track_status" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label-width="120px" label="下次跟进时间" prop="nextTime">
                <el-date-picker type="datetime" v-model="form.nextTime" placeholder="请输入下次跟进时间" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="沟通重点" prop="communicationPoints">
                <el-select multiple v-model="form.communicationPoints" placeholder="请输入沟通重点">
                  <el-option v-for="dict in dict.type.communication_point" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label-width="120px" label="沟通纪要" prop="record">
                <el-input type="textarea" show-word-limit v-model="form.record" maxlength="100" placeholder="请输入沟通纪要" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="display: flex; direction: rtl;">
          <el-button  style="margin-left: 5px;" type="info" @click="cancel">取消</el-button>
          <el-button style="margin-left: 5px;" v-if="!disabled && (business.status == 1 || business.status == 2)" type="success" @click="handleTransform">转交成客户</el-button>
          <el-button v-if="!disabled && (business.status == 1 || business.status == 2)" type="danger" @click="handleFakeClue">踢回公海</el-button>
          <el-button v-if="!disabled && (business.status == 1 || business.status == 2)" type="primary" @click="submitForm">保存</el-button>
        </div>
      </el-col>
      <el-col :span="6">
        <track-list :key="componentKeys.trackListKey" :id="businessId"></track-list>
      </el-col>
    </el-row>
    <!-- 踢回公海   -->
    <give-back ref="giveBack"
               :businessId="businessId"
               @success="ok"></give-back>
    <transform ref="transform"
               :businessId="businessId"
               @success="ok"></transform>
  </div>
</template>

<script>
import { addBusinessTrack } from "@/api/crm/businessTrack";
import { getBusiness } from "@/api/crm/business";
import {listCourse} from "@/api/crm/course";
import { listAssignRecord } from "@/api/crm/assignRecord";
import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'
import Transform from '@/views/crm/business/operation/transform'
import GiveBack from '@/views/crm/business/operation/give-back'
import TrackList from '@/views/crm/business/operation/track-list'

export default {
  name: "BusinessTrack",
  dicts: ['reasons_for_reporting', 'clues_item', 'sys_user_sex', 'clues_level',
    'occupation','education','major','course_subject','track_status',
    'job','communication_point','salary','reasons_for_business_reporting'
  ],
  components: {Transform, GiveBack, TrackList},
  props: {
    businessId: [String, Number],
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      componentKeys: {
        trackListKey: 0,
        giveBackKey: 0,
        transformKey: 0,
      },
      business: {},
      assignRecord: {},
      provinceAndCityDataOptions: provinceAndCityData,
      // 表单参数
      form: {
        price: null,
        communicationPoints: [],
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        subject: [
          { required: true, message: "意向学科不能为空", trigger: "change" },
        ],
        courseId: [
          { required: true, message: "意向课程不能为空", trigger: "change" },
        ],
        communicationPoints: [
          { required: true, message: "沟通重点不能为空", trigger: "blur" },
        ],
        trackStatus: [
          { required: true, message: "跟进状态不能为空", trigger: "blur" },
        ],
        record: [
          { required: true, message: "沟通纪要不能为空", trigger: "blur" },
        ],
        nextTime: [
          { required: true, message: "下次跟进时间不能为空", trigger: "blur" },
        ],
      },
      courseOptions: []
    };
  },
  created() {
     this.refreshData();
  },
  watch: {
    businessId: {
      handler(newValue, oldValue) {
        this.refreshData()
      },
      immediate: true
    }
  },
  methods: {
    refreshData() {
      this.getBusiness()
      this.getAssignRecord()
      this.refreshTrackList()
    },
    getBusiness() {
      getBusiness(this.businessId).then(resp=>{
        this.business = resp.data
        this.form = this.business
        // 根据ID设置意向课程下拉列表
        listCourse({subject: this.form.subject}).then(resp => {
          this.courseOptions = resp.rows;
        })
        // 设置省市下拉列表的值
        if (this.form.provinces && this.form.city) {
          this.form.area = [TextToCode[this.form.provinces].code, TextToCode[this.form.provinces][this.form.city].code]
        }
      })
    },
    getAssignRecord() {
      // 简单调用自动生成的分页代码，取最大id的对象当作最近的分配记录
      listAssignRecord({assignId: this.businessId, type: 1, pageNum: 1, pageSize: 5, orderByColumn: 'id', isAsc: 'desc'}).then(resp => {
        if(resp.rows && resp.rows.length > 0) {
          this.assignRecord = resp.rows.reduce((a1, a2) => { return a1.id > a2.id ? a1 : a2});
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        phone: null,
        channel: null,
        activityId: null,
        provinces: null,
        city: null,
        sex: null,
        age: null,
        weixin: null,
        qq: null,
        level: null,
        subject: null,
        courseId: null,
        createBy: null,
        createTime: null,
        occupation: null,
        education: null,
        job: null,
        salary: null,
        major: null,
        expectedSalary: null,
        reasons: null,
        plan: null,
        planTime: null,
        otherIntention: null,
        status: "0",
        nextTime: null,
        lastUpdateTime: null,
        clueId: null,
        transfer: null,
        remark: null,
        endTime: null,
        price: null,
        communicationPoints: [],
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.keyItems = this.form.communicationPoints.join(",")
          addBusinessTrack(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.refreshData();
            this.componentKeys.trackListKey += 1;
            this.$emit('success')
          });
        }
      });
    },
    cancel() {
      this.$emit('cancel');
    },
    ok() {
      this.$emit('success');
      this.refreshData();
      this.componentKeys.trackListKey++;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除线索编号为"' + ids + '"的数据项？').then(function() {
        return delClue(ids);
      }).then(() => {
        this.getBusiness();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/clue/export', {
        ...this.queryParams
      }, `clue_${new Date().getTime()}.xlsx`)
    },

    handleFakeClue() {
      this.$refs.giveBack.open = true;
      this.$refs.giveBack.resetForm();
    },
    handleTransform() {
      this.$refs.transform.resetForm()
      this.$refs.transform.dialogVisible = true
    },
    handleChangeArea(value) {
      if (value && value.length > 0) {
        this.form.provinces = CodeToText[value[0]]
        this.form.city = CodeToText[value[1]]
      } else {
        this.form.provinces = ''
        this.form.city = ''
      }
    },
    handleChangeSubject(value) {
      this.form.courseId = null;
      this.form.price = null;
      listCourse({subject: value}).then(resp => {
        this.courseOptions = resp.rows;
      })
    },
    handleChangeCourse(id) {
      const course = this.courseOptions.find(item => item.id == id)
      if(course) {
        this.form.price = course.price
      }
    },
    refreshTrackList() {
      this.componentKeys.trackListKey += 1;
      this.$emit('success')
    },
  }
};
</script>
